package com.app.oral.controller

import com.app.oral.config.ApiResponse
import com.app.oral.model.AccountStatus
import com.app.oral.service.UserService
import com.app.oral.service.ClassService
import com.app.oral.service.UserSessionService
import com.app.oral.util.UserResponseHelper
import org.springframework.web.bind.annotation.*
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpSession
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.responses.ApiResponse as SwaggerApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import io.swagger.v3.oas.annotations.tags.Tag
import io.swagger.v3.oas.annotations.security.SecurityRequirement

@RestController
@RequestMapping("/api/v1/auth")
@Tag(name = "认证管理", description = "用户登录、退出、会话管理接口")
class LoginController(
    private val userService: UserService,
    private val classService: ClassService,
    private val userSessionService: UserSessionService
) {

    @Operation(
        summary = "微信小程序登录",
        description = "通过微信OpenID创建用户会话，支持自动创建新用户"
    )
    @ApiResponses(value = [
        SwaggerApiResponse(responseCode = "200", description = "登录成功，返回会话Token和用户信息"),
        SwaggerApiResponse(responseCode = "400", description = "微信身份验证失败")
    ])
    @SecurityRequirement(name = "WeChatAuth")
    @PostMapping("/wx/login")
    fun wxLogin(
        @Parameter(hidden = true) request: HttpServletRequest
    ): ApiResponse<Map<String, Any>> {
        val openid = request.getHeader("X-WX-OPENID")
        val nickname = request.getHeader("X-WX-NICKNAME") ?: ""
        val avatarUrl = request.getHeader("X-WX-AVATARURL") ?: ""

        if (openid.isNullOrEmpty()) {
            return ApiResponse.error("微信身份验证失败")
        }

        // 获取或创建用户
        val user = userService.getOrCreateUser(openid, nickname, avatarUrl)
        if (user.id == null) {
            return ApiResponse.error("用户创建失败")
        }

        // 先清除该用户的旧会话（单设备登录）
        userSessionService.logoutByOpenid(openid)

        // 创建新的会话
        val session = userSessionService.createSession(user.id, openid)
        
        // 更新最后登录时间
        userService.updateLastLoginTime(openid)
        
        // 获取班级信息
        val className = user.classId?.let { classId ->
            classService.getClassById(classId)?.className
        }
        
        val userWithClassName = UserResponseHelper.buildUserResponse(user, className)
        
        val response = mutableMapOf(
            "sessionToken" to session.sessionKey,
            "user" to userWithClassName,
            "needCompleteProfile" to (user.accountStatus == AccountStatus.INCOMPLETE),
            "isPending" to (user.accountStatus == AccountStatus.PENDING),
            "isApproved" to (user.accountStatus == AccountStatus.APPROVED),
            "isRejected" to (user.accountStatus == AccountStatus.REJECTED)
        )

        return ApiResponse.ok("登录成功", response)
    }

    @Operation(
        summary = "管理后台登录",
        description = "使用用户名密码登录管理后台"
    )
    @ApiResponses(value = [
        SwaggerApiResponse(responseCode = "200", description = "登录成功"),
        SwaggerApiResponse(responseCode = "400", description = "用户名或密码错误")
    ])
    @PostMapping("/admin/login")
    fun adminLogin(
        @Parameter(description = "管理员用户名") @RequestParam username: String,
        @Parameter(description = "管理员密码") @RequestParam password: String,
        @Parameter(hidden = true) session: HttpSession
    ): ApiResponse<Map<String, Any>> {
        // 简单的硬编码验证
        return if (username == "admin" && password == "admin123") {
            session.setAttribute("adminLoggedIn", true)
            ApiResponse.ok("登录成功", mapOf("redirectUrl" to "/admin/dashboard"))
        } else {
            ApiResponse.error("用户名或密码错误")
        }
    }

    @Operation(
        summary = "退出登录",
        description = "同时处理微信小程序和管理后台的退出登录"
    )
    @ApiResponses(value = [
        SwaggerApiResponse(responseCode = "200", description = "退出成功")
    ])
    @PostMapping("/logout")
    fun logout(
        @Parameter(hidden = true) request: HttpServletRequest,
        @Parameter(hidden = true) session: HttpSession
    ): ApiResponse<String> {
        // 处理微信小程序会话
        val sessionKey = request.getHeader("Authorization")?.removePrefix("Bearer ")
        if (!sessionKey.isNullOrEmpty()) {
            val userSession = userSessionService.validateSession(sessionKey)
            if (userSession != null) {
                userSessionService.deactivateSession(sessionKey)
            }
        }
        
        // 处理管理后台会话
        session.invalidate()
        
        return ApiResponse.ok("退出登录成功")
    }

    @Operation(
        summary = "检查登录状态",
        description = "检查微信和管理后台的登录状态"
    )
    @ApiResponses(value = [
        SwaggerApiResponse(responseCode = "200", description = "状态检查完成")
    ])
    @GetMapping("/check-status")
    fun checkLoginStatus(
        @Parameter(hidden = true) request: HttpServletRequest,
        @Parameter(hidden = true) session: HttpSession
    ): ApiResponse<Map<String, Any>> {
        val openid = request.getHeader("X-WX-OPENID")
        val isAdminLoggedIn = session.getAttribute("adminLoggedIn") as Boolean? ?: false
        
        // 检查微信登录状态
        val wxLoginStatus = if (openid.isNullOrEmpty()) {
            mapOf(
                "hasWechatAuth" to false,
                "hasActiveSession" to false,
                "needLogin" to true
            )
        } else {
            // 检查是否有活跃会话
            val activeSession = userSessionService.hasActiveSession(openid)
            
            mapOf(
                "hasWechatAuth" to true,
                "hasActiveSession" to (activeSession != null),
                "needLogin" to (activeSession == null),
                "sessionToken" to (activeSession?.sessionKey ?: "")
            )
        }
        
        val response = mutableMapOf<String, Any>(
            "wx" to wxLoginStatus,
            "admin" to mapOf("isLoggedIn" to isAdminLoggedIn)
        )

        return ApiResponse.ok("检查完成", response)
    }

    @Operation(
        summary = "获取用户信息",
        description = "根据会话Token获取当前用户详细信息"
    )
    @ApiResponses(value = [
        SwaggerApiResponse(responseCode = "200", description = "获取成功"),
        SwaggerApiResponse(responseCode = "401", description = "会话无效或已过期")
    ])
    @SecurityRequirement(name = "BearerAuth")
    @GetMapping("/user-info")
    fun getUserInfo(
        @Parameter(hidden = true) request: HttpServletRequest
    ): ApiResponse<Map<String, Any>> {
        val sessionKey = request.getHeader("Authorization")?.removePrefix("Bearer ")
            ?: return ApiResponse.error("缺少会话令牌")

        // 验证会话
        val session = userSessionService.validateSession(sessionKey)
            ?: return ApiResponse.error("会话无效或已过期，请重新登录")

        // 更新会话访问时间
        userSessionService.updateSessionAccess(sessionKey)

        // 获取用户信息
        val user = userService.getOrCreateUser(session.openid)
        
        // 获取班级信息
        val className = user.classId?.let { classId ->
            classService.getClassById(classId)?.className
        }
        
        val userWithClassName = UserResponseHelper.buildUserResponse(user, className)
        
        val response = mutableMapOf(
            "user" to userWithClassName,
            "needCompleteProfile" to (user.accountStatus == AccountStatus.INCOMPLETE),
            "isPending" to (user.accountStatus == AccountStatus.PENDING),
            "isApproved" to (user.accountStatus == AccountStatus.APPROVED),
            "isRejected" to (user.accountStatus == AccountStatus.REJECTED)
        )

        return ApiResponse.ok("获取用户信息成功", response)
    }
}